import React from "react";
import ReactDOM from 'react-dom';
import { deepCopy, messages } from 'share/common';
import { Modal, Checkbox, Popconfirm, Icon, Button } from 'antd';
import { LanguageInput } from 'components/index';
import "styles/data-center/report/travel-report/components/report-fields-editor/index.scss";
import withDragDropContext from 'components/with-dnd-context';
import DragFieldItem from "containers/data-center/report/travel-report/components/report-fields-editor/drag-field-item"
import TRSService from 'containers/data-center/report/travel-report/travel-report-setting.service';

class ReportFieldEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      codeVisible: false,
      currentFields: [],
      i18nCache: null,
      sorted: false,
      isSubmitting: false
    };
  }

  componentDidUpdate(nextProps) {
    if ((!this.state.currentFields.length && nextProps.fields.length)
      || nextProps.fields !== this.props.fields) {
      this.setState({
        currentFields: [].concat(nextProps.fields),
      })
    }
  }

  handleClose = () => {
    const { onClose, fields } = this.props;
    this.setState({
      currentFields: [].concat(fields),
      sorted: false
    });
    onClose();
  };

  handleOk = () => {
    const { onSave } = this.props;
    let { sorted, currentFields } = this.state;
    if (sorted) {
      currentFields.forEach((field, index) => {
        field.columnSeqNo = index + 1;
      })
    }
    this.setState({
      isSubmitting: true,
      sorted: false
    }, () => {
      TRSService.updateReportColumn(currentFields).then(() => {
        this.setState({
          isSubmitting: false
        });
        onSave(currentFields);
      }).catch(e => {
        this.setState({
          isSubmitting: false,
          sorted
        });
      })
    });
  };

  handleCodeVisibleChange = () => {
    const { codeVisible } = this.state;
    this.setState({
      codeVisible: !codeVisible
    })
  };

  handleFieldVisibleChange = (e, field) => {
    let visible = e.target.checked;
    field.hide = !visible;
    this.setState({ field })
  };

  renderLanguage = (field) => {
    let { i18n, columnDisplayName } = field;
    return (
      <span className="language-edit-icon">
        <Icon type="edit" onClick={(e) => this.showEditName(e, field)}/>
        <Popconfirm
          title={<div>
            <LanguageInput
              name={columnDisplayName}
              i18nName={i18n && i18n.columnDisplayName ? i18n.columnDisplayName : null}
              nameChange={(name, i18nName) => this.i18nNameChange(name, i18nName, field)}
              isEdit={true}
            />
          </div>}
          overlayClassName="report-field-pop-confirm"
          visible={field.editName}
          onConfirm={(e) => this.nameSaveConfirm(e, field)}
          onCancel={(e) => this.nameSaveCancel(e, field)}
          overlayStyle={{ width: 200 }}
          placement='top'
          okText={messages("common.save")/*保存*/}
          cancelText={messages("common.cancel")/*取消*/}/>
    </span>
    )
  };

  //显示编辑名字
  showEditName = (e, field) => {
    if (field.editName) {
      return;
    }
    let { currentFields } = this.state;
    let i18nCache = deepCopy(field);
    currentFields = currentFields.map(item => {
      item.editName = item.id === field.id;
      return item;
    });
    this.setState({
      currentFields,
      i18nCache
    })
  };

  //名字输入多语言
  i18nNameChange = (name, i18nName, field) => {
    field.columnDisplayName = name;
    field.i18n.columnDisplayName = i18nName;
    this.setState({ field });
  };

  //保存修改的名字
  nameSaveConfirm = (e, field) => {
    field.editName = false;
    this.setState({ field });
  };

  //取消修改名字
  nameSaveCancel = (e, field) => {
    field.editName = false;
    Object.assign(field, this.state.i18nCache);
    this.setState({ field });
  };

  handleDND = (dragIndex, targetIndex) => {
    let { currentFields } = this.state;
    if (targetIndex >= currentFields.length) return;
    let temp = currentFields.splice(dragIndex, 1)[0]; // 删除并临时储存
    currentFields.splice(targetIndex, 0, temp); // 插入放置项
    this.setState({
      currentFields,
      sorted: true
    })
  };


  render() {
    const { visible, draggable } = this.props;
    const { codeVisible, currentFields, isSubmitting } = this.state;
    const {
      renderLanguage,
      handleClose,
      handleOk,
      handleCodeVisibleChange,
      handleFieldVisibleChange,
      handleDND
    } = this;
    let className = `report-fields-list ${currentFields.length > 1 && 'more-than-two'}`;
    return (
      <Modal
        className="report-field-editor-wrapper"
        width={900}
        title={messages('data-center.key15'/*字段编辑*/)}
        visible={visible}
        onCancel={handleClose}
        maskClosable={false}
        keyboard={false}
        closable={false}
        footer={null}>
        <div>
          <Checkbox
            checked={codeVisible}
            onChange={handleCodeVisibleChange}>
            {messages('data-center.key139')/*显示字段唯一标识*/}
          </Checkbox>
          <div className={className}>
            {currentFields.map((field, index) => {
              return (
                <DragFieldItem
                  field={field}
                  handleFieldVisibleChange={handleFieldVisibleChange}
                  codeVisible={codeVisible}
                  renderLanguage={renderLanguage}
                  handleDND={handleDND}
                  draggable={draggable}
                  index={index}/>
              )
            })}
          </div>
          <br/>
          <div>
            <Button onClick={handleOk} type="primary" loading={isSubmitting}>
              {messages('common.ok')}
            </Button>
            &nbsp;&nbsp;&nbsp;
            <Button onClick={handleClose} disabled={isSubmitting}>
              {messages('common.cancel')}
            </Button>
          </div>
        </div>
      </Modal>
    )
  }

}


ReportFieldEditor.propTypes = {
  visible: React.PropTypes.bool,  // 对话框是否可见
  draggable: React.PropTypes.bool,  // 是否可拖拽
  fields: React.PropTypes.array.isRequired,  // 字段数组
  onClose: React.PropTypes.func,
  onSave: React.PropTypes.func,
};

ReportFieldEditor.defaultProps = {
  draggable: true,
};

export default withDragDropContext(ReportFieldEditor)
